<?php
class companyOrder extends common {
    var $order_table = "company_order";

    //订单交易状态
    var $trading_status = array(
        1 => '进行中' , 2 => '成功' , 3 => '失败'
        );
    //支付状态
    var $pay_status = array(
        1 => '待支付' , 2 => '已支付' , 3 => '到账' , 4 => '退款成功' , '5' => '交易完成'
        );
    //支付类型
    var $pay_style = array(1 => '微信' , 2 => '支付宝' , 3 => '银联'); 

   function __construct(){
        parent::__construct();
    }
	//生成订单
	function creatOrders($param){
		 extract($param);
		 $sql="company_product where id=".$product_id;
		 $res=$this->getInfo($sql,'id,company_id,price');
		 //购买钱数
		 $price=intval($number)*($res['price']);
		 if($res['id']!='' && $res['id']!=null){
			 $date = date('Y-m-d h:i:s');
			 $data=array('product_id'=>$product_id,'user_id'=>$user_id,'company_id'=>$res['company_id'],'order_date'=>$date,'amount'=>$number,'pay_money'=>$price,'pay_status'=>'1','province'=>$province,'city'=>$city,'county'=>$county,'address'=>$address,'consignee'=>$consignee,'remarks'=>$remarks,'phone'=>$phone);
			 //插入数据库
			 $this->insert('company_order',$data);
			 $id = $this->insert_id();
			 
		 }
		 return array('order_id'=>$id);
		 	
	}
	//用户的待支付订单列表
	function userNotpayOrder($param){
		extract($param);
		if($user_id!=''){
			$sql="company_product p left join ".$this->order_table." o  on p.id=o.product_id left join companies c on o.company_id=c.id where o.pay_status=1 and o.user_id=".$user_id;
			$res=$this->getList($sql,'p.name,p.img_0,p.price,o.*,c.title',$num,$page);

		}
		return $res;
	}
	//用户的已支付订单列表
	function userOrderList($param){
		extract($param);
		if($user_id!=''){
			$sql="company_product p left join ".$this->order_table." o  on p.id=o.product_id left join companies c on o.company_id=c.id where o.pay_status=2 and o.user_id=".$user_id;
			$res=$this->getList($sql,'p.name,p.img_0,p.price,o.*,c.title',$num,$page);

		}
		return $res;
	}
    function confirmTradingSuccess($param) {
        $error = '0';
        extract($param);
        $date = date('Y-m-d h:i:s');
        $data = array('trading_status'=>2,'trade_success_date'=>$date);
        $sql = $this->order_table." where id = '".$order_id."'";
        $info = $this->getInfo($sql, 'id,company_id,order_date');
         
        if($info['id']==''||$info['id']==null)
        {
             $error = '1';
             $msg = "order_id = '".$order_id. "'订单不存在";
        }
        $where =  " id = '".$order_id."'";
        if ($error ==0)
        {
            $error = $this->update($this->order_table, $data, $where);
            if( $error)
            {
                $error = '0';
                $msg = '成功';
                $this->createCompanyAccount( $date,$info['company_id']);
            }
            else
            {
                $error = '1';
                $msg = '失败';
            }
            
        }
        return array('error'=>$error,'msg'=>$msg);
    }
    
    function addNewOrder($param) {
        extract($param);
        
    }
    
    function createCompanyAccount($date='',$company_id='') {
        
        /**
         * 获取公司名称 本月成功交易金额
         */
	$where = " where trading_status = 2 and  DATE_FORMAT(trade_success_date,'%Y-%m') = '".date('Y-m',strtotime($date))."' and DATE_FORMAT(order_date,'%Y-%m') = '".date('Y-m',strtotime($date))."'and company_id ='".$company_id."' group by company_id";
	$sql = $this->order_table;
	$sql.= $where;
        $key = "DATE_FORMAT(order_date,'%Y-%m') as account_date,company_id,sum(pay_money) as traded_money";
       
//       $row= $this->getInfo($sql, $key);
       $row= $this->getList($sql, $key);
      
       
      /**
         * 获取本月交易中交易金额
         */
        if(is_array($row['result']))
        {
            foreach ($row['result'] as $k => $value) {
              
               $where = " where trading_status = 1 and  DATE_FORMAT(trade_success_date,'%Y-%m') <> '".date('Y-m',strtotime($date))."' and DATE_FORMAT(order_date,'%Y-%m') = '".date('Y-m',strtotime($date))."'and company_id ='".$value['company_id']."' group by company_id";
	       $sql = $this->order_table;
	       $sql.= $where;
               $key = "company_id,sum(pay_money) as trading_money";
               $result = $this->getInfo($sql, $key);
                $trading_money = $result['trading_money'];
                $value['trading_money']=$trading_money;
                $row['result'][$k] = $value;
                
            }
          
        } 
        
         /**
         * 获取上月剩余金额
         */
      
        if(is_array($row['result']))
        {
            foreach ($row['result'] as $k => $value) {
                 
                 $where = " where trading_status = 2 and  DATE_FORMAT(trade_success_date,'%Y-%m') = '".date('Y-m',strtotime($date))."' and DATE_FORMAT(order_date,'%Y-%m') <> '".date('Y-m',strtotime($date))."'and company_id ='".$value['company_id']."' group by company_id";
	         $sql = $this->order_table;
	         $sql.= $where;
                 $key = "sum(pay_money) as remain_money";
                 $result = $this->getInfo($sql, $key);
                 $trading_money = $result['remain_money'];
                 $value['remain_money'] = $trading_money;
                 $value['sum_money'] = $trading_money + $value['traded_money']; 
                 $row['result'][$k] = $value;
                
            }
          
        }  
        if(is_array($row['result']))
        {
            foreach ($row['result'] as $k => $value) {
                var_dump($value);
                  $sql = " companies_accounting where type=1 and company_id = '".$value['company_id']."'and DATE_FORMAT(date,'%Y-%m')='".$value['account_date']."'";
                  $key = "id";
                  $check_account = $this->getInfo($sql,$key);
                   var_dump( $check_account);
                  if($check_account['id'])
                  {
                        $data = array('sum_money'=>$value['sum_money'],'last_remainprofit'=>$value['remain_money'],'this_profit'=>$value['traded_money']);
                        $this->update("companies_accounting",$data,"id = '".$check_account['id']."'");
                      
                  }
                  else
                  {
                       $data = array('sum_money'=>$value['sum_money'],'last_remainprofit'=>$value['remain_money'],'this_profit'=>$value['traded_money'],'type'=>1,'state'=>1,'company_id'=>$value['company_id'],'date'=>$value['account_date']."-00 00:00:00",'closing_date'=>'0000-00-00 00:00:00');
                       
                        $inset_res = $this->insert("companies_accounting", $data);
                       
                  }
                
            }
          
       }  
       
         
     }
	
	
	/*
	* 添加收货地址
	*/
    function addAddress($param){
	   extract($param);
	   if($user_id!=''){
		   $data = array('user_id'=>$user_id,'province'=>$province,'city'=>$city,'county'=>$area,'phone'=>$phone,'tell'=>$tell,'code'=>$code,'name'=>$name,'address'=>$address,'is_default'=>$is_default);
		   if($is_default=='1'){
			   //查找默认地址
			$sql="update user_address SET is_default=0 where user_id=".$user_id." and is_default=1";
			mysql_query($sql);
			$this->insert('user_address',$data);
			$error="0";
			$msg="默认地址修改成功";
		   }else{
			$this->insert('user_address',$data);
			$error="0";
			$msg="添加成功";  
		   }			
	   }
	   return array('error'=>$error,'msg'=>$msg);
   }
   
    /*
	*收货地址列表
	*/
   function AddressList($param){
	   extract($param);
	   if($user_id!=''){
			$sql="user_address where user_id=".$user_id." order by is_default DESC";
			$res=$this->getList($sql, $key="*", $num,$page);
			return $res;
			//print_r($res);
	   }
   }
	/*
	* 编辑收货地址
	*/
	function editReceAddress($param){
		extract($param);
		if($id){
			$sql=" user_address where id=".$id;
			$res=$this->getInfo($sql);
			if($res['id']!=''){
					$data = array('province_id'=>$province_id,'province'=>$province,'city_id'=>$city_id,'city'=>$city,'county_id'=>$county_id,'county'=>$county,'phone'=>$phone,'name'=>$name,'address'=>$address,'is_default'=>$is_default);
					$this->update('user_address',$data,"id='".$id."'");
					$error="0";
					$msg="编辑成功";

			}
		}
		return array('msg'=>$msg,'error'=>$error);
	}
	
	/*
	* 删除收货地址
	*/
	function delReceAddress($param){
		extract($param);
		if($id){
			$sql1=" user_address where id=".$id;
			$res=$this->getInfo($sql1, $key='*',$debug='0');
			if($res['is_default']=='1'){
				$error="1";
				$msg="不能删除默认地址";
			}else{
			$sql="delete from user_address where id=".$id;
			$cc=mysql_query($sql);
			if($cc){
			$error='0';
			$msg='删除成功';
			}
			}
		}
		return array('error'=>$error,'msg'=>$msg);
	}
	//设为默认地址
	function setDefault($param){
		extract($param);
		$sqls=" user_address where id=".$id." and user_id=".$user_id;
		$row=$this->getInfo($sqls);
		if($row['id']!=''){
			$sql=" user_address where is_default=1 and user_id=".$user_id;
			$res=$this->getInfo($sql);
			$sql="update user_address SET is_default=0 where id=".$res['id']." and is_default=1 "; 
			mysql_query($sql);
			$data=array('is_default'=>'1');
			$this->update('user_address', $data, "id='".$id."'");
			$error='0';
			$msg="设为默认地址成功";
			
		}else{
			$error='1';
			$msg="不存在";
		}
		return array('msg'=>$msg,'error'=>$error);
		
	}   

	

}
